package com.zz.normal.util.image;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import com.zz.normal.framework.ZConfiguration;
import com.zz.normal.util.log.Mylog;

public class ZLNetworkManager {

	private static ZLNetworkManager ourManager;

	public static ZLNetworkManager Instance() {
		if (ourManager == null) {
			ourManager = new ZLNetworkManager();
		}
		return ourManager;
	}

	public final String downloadToFile(String url, final File outFile) {
		return downloadToFile(url, outFile, 8192);
	}

	public final String downloadToFile(String _url, final File outFile,final int bufferSize) {
		HttpURLConnection httpConnection = null;
		try {
			Mylog.d("ZLNetworkManager", "begin download "+_url);
			httpConnection = ZConfiguration.getInstance().getHttpURLConnection(_url,"GET","application/x-www-form-urlencoded","");
			httpConnection.connect();
			int response = httpConnection.getResponseCode();
			if (response == HttpURLConnection.HTTP_OK) {
				
				InputStream inputStream = httpConnection.getInputStream();
				OutputStream outStream = new FileOutputStream(outFile);
				try {
					final byte[] buffer = new byte[bufferSize];
					while (true) {
						final int size = inputStream.read(buffer);
						if (size <= 0) {
							break;
						}
						outStream.write(buffer, 0, size);
					}
				} finally {
					outStream.close();
					inputStream.close();
				}
				Mylog.d("ZLNetworkManager", "success download "+_url);
			}else{
				Mylog.d("ZLNetworkManager", "fail download "+_url);
			}

		} catch (IOException e) {

			return e.getMessage();
		}

		return null;

	}
	
}
